import React, { useState, useEffect } from 'react';
import { Button, Upload, message, List } from 'antd';
import { UploadOutlined, DownloadOutlined } from '@ant-design/icons';
import request from 'umi-request';

const FilePage: React.FC = () => {
    const [fileList, setFileList] = useState<any[]>([]); // 已上传文件列表
    const [uploadedFiles, setUploadedFiles] = useState<string[]>([]); // 从后端获取的文件列表

    // 获取文件列表
    const fetchFileList = async () => {
        try {
            const response = await request('http://localhost:3000/api/files');
            if (response && response.files) {
                setUploadedFiles(response.files); // 更新文件列表状态
            }
        } catch (error) {
            message.error('获取文件列表失败');
        }
    };

    // 初始化时获取文件列表
    useEffect(() => {
        fetchFileList();
    }, []);

    // 文件上传配置
    const uploadProps = {
        name: 'file',
        action: 'http://localhost:3000/api/upload', // 上传接口地址
        headers: {
            authorization: 'authorization-text',
        },
        onChange(info: any) {
            if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            if (info.file.status === 'done') {
                message.success(`${info.file.name} 文件上传成功`);
                setFileList(info.fileList);
                fetchFileList(); // 上传成功后刷新文件列表
            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} 文件上传失败`);
            }
        },
        onRemove(file: any) {
            setFileList(fileList.filter((item) => item.uid !== file.uid));
        },
    };

    // 文件下载
    const handleDownload = (filename: string) => {
        const url = `http://localhost:3000/api/download/${filename}`; // 下载接口地址
        window.open(url, '_blank');
    };

    return (
        <div style={{ padding: 24 }}>
            <h1>文件管理</h1>

            {/* 文件上传组件 */}
            <Upload {...uploadProps} fileList={fileList}>
                <Button icon={<UploadOutlined />}>上传文件</Button>
            </Upload>

            {/* 已上传文件列表 */}
            <div style={{ marginTop: 16 }}>
                <h3>已上传文件列表</h3>
                <List
                    dataSource={uploadedFiles}
                    renderItem={(file) => (
                        <List.Item
                            actions={[
                                <Button
                                    type="link"
                                    icon={<DownloadOutlined />}
                                    onClick={() => handleDownload(file)}
                                >
                                    下载
                                </Button>,
                            ]}
                        >
                            <List.Item.Meta title={file} />
                        </List.Item>
                    )}
                />
            </div>
        </div>
    );
};

export default FilePage;